CSE 373: Data
Structures and Algorithms
Winter 2000
Assignment 3 Chapter 4
Solutions
_________________
(_______22:-______)
/ \
/ \
____ _/ \_______
( 16:- ) ( 41:58 )
/ \
/ | \
____/____ _\_____ __________/ ___|___ \__________
[ 8,11,12 ] [ 16,17 ] [
22,23,31 ] [ 41,52 ] [ 58,59,61 ]
Here's the
solution by Jindong Fang. Your TA is too lazy to draw the graph.
5pts for (1) & (2), 10
pts for (3) & (4).
Subtree
predecessor:
return the
rightmost node of the left subtree of the given node.
node* subtree_predecessor(node* p)
{
if (!p->left)
return NULL;
node* pItr=p->left;
while
(pItr->right!=NULL)
pItr=pItr->right;
return pItr;
}
Subtree
successor:
return the
leftmost node of the right subtree of the given node.
node* subtree_successor(node* p)
{
if (!p->right)
return NULL;
node* pItr=p->right;
while
(pItr->left!=NULL)
pItr=pItr->left;
return pItr;
}
Complete
tree predecessor
If there
is a subtree predecessor, return the subtree predecessor.
else trace
up the tree by following the parent pointers until you see a node is the right
child of its parent, i.e. until you see a node whose value is smaller than the
given node's. If the root is reached before you find such a node, that means
the given node is the leftmost node of the whole tree, it has no predecessor.
node* completetree_predecessor(node* p)
{
node*
pItr=subtree_predecessor(*p);
if (pItr)
return pItr;
pItr=p->parent;
while (pItr!=NULL
&& pItr->data>=p->data)
pItr=pItr->parent;
return pItr;
}
Complete
Tree Successor:
If there
is a subtree successor, return the subtree successor.
else trace
up the tree by following the parent pointers until you see a node is the left
child of its parent, i.e. until you see a node whose value is greater than the
given node's. If the root is reached before you find such a node, that means
the given node is the rightmost node of the whole tree, it has no successor.
node* completetree_successor(node* p)
{
node*
pItr=subtree_successor(*p);
if (pItr)
return pItr;
pItr=p->parent;
while (pItr!=NULL
&& pItr->data<=p->data)
pItr=pItr->parent;
return pItr;
}